package com.screen.screendisplay.service.impl.dryport;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.screen.screendisplay.entity.dryport.DryportSafetyenvSkylight;
import com.screen.screendisplay.mapper.dryport.DryportSafetyenvSkylightMapper;
import com.screen.screendisplay.service.dryport.DryportSafetyenvSkylightService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.screen.screendisplay.vo.dryport.SkylightVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * <p>
 * 天窗检修情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class DryportSafetyenvSkylightServiceImpl extends ServiceImpl<DryportSafetyenvSkylightMapper, DryportSafetyenvSkylight> implements DryportSafetyenvSkylightService {

    @Override
    public SkylightVO getSkylightStatistics(Integer year) {
        // 设置默认年份为2025
        if (year == null) {
            year = 2025;
        }
        
        // 查询指定年份的数据
        LambdaQueryWrapper<DryportSafetyenvSkylight> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportSafetyenvSkylight::getYear, year);
        queryWrapper.last("LIMIT 1"); // 只取一条记录
        DryportSafetyenvSkylight entity = this.getOne(queryWrapper);
        
        SkylightVO vo = new SkylightVO();
        
        // 如果没有数据，返回空对象
        if (entity == null) {
            return vo;
        }
        
        // 设置各个字段的值
        vo.setSkylightPlanned(entity.getSkylightPlanned());
        vo.setSkylightCompleted(entity.getSkylightCompleted());
        vo.setTempSkylightCompleted(entity.getTempSkylightCompleted());
        
        // 如果数据库中已经有完成率，直接使用；否则计算
        if (entity.getCompletionRate() != null) {
            vo.setCompletionRate(entity.getCompletionRate());
        } else if (entity.getSkylightPlanned() != null && entity.getSkylightPlanned() > 0 
                   && entity.getSkylightCompleted() != null) {
            // 计算检修完成率 = 完成量 / 计划量 * 100
            BigDecimal completionRate = new BigDecimal(entity.getSkylightCompleted())
                .divide(new BigDecimal(entity.getSkylightPlanned()), 4, RoundingMode.HALF_UP)
                .multiply(new BigDecimal(100));
            vo.setCompletionRate(completionRate);
        }
        
        return vo;
    }

}
